package com.example.demo.controller.admin;


import com.example.demo.entity.Role;
import com.example.demo.pojo.BSResult;
import com.example.demo.service.RolePrivilegeService;
import com.example.demo.service.RoleService;
import com.example.demo.service.UserRoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequiresPermissions("role-manage")
@RequestMapping("/admin/role")
public class AdminRoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePrivilegeService rolePrivilegeService;

    @RequestMapping("/list")
    public String roleList(Model model){
        List<Role> allRoles=roleService.findAllRoles();
        model.addAttribute("allRoles",allRoles);
        return "/admin/role/list";
    }

    @RequestMapping("/toAddition")
    public  String toAddition(){
        return "/admin/role/add";
    }

    @RequestMapping("/addition")
    public String addRole(Role role){
    roleService.addRole(role);
    return "forward:list";
    }

    @RequestMapping("/deletion/{roleId}")
    public String deleteRole(@PathVariable(value = "roleId")String roleId){
        Integer roleIds=Integer.parseInt(roleId);
        userRoleService.deleteByRoleId(roleIds);
        rolePrivilegeService.deleteByRoleId(roleIds);
        roleService.deleteByRoleId(roleIds);
        return "forward:/admin/role/list";
    }

    @RequestMapping("/echo/{roleId}")
    public String echoRole(@PathVariable(value = "roleId")String roleId, Model model){

        Role role=roleService.findRoleById(Integer.parseInt(roleId));
        model.addAttribute("role",role);

        return "/admin/role/edit";
    }

    @RequestMapping("/update")
    public String updateRole(Role role,Model model){
        try {
            roleService.updateRole(role);
            model.addAttribute("saveMsg","修改成功");
        }catch(Exception e){

        }

        return "forward:echo/"+role.getRole_id();
    }


    @RequestMapping("/updatePrivilege")
    @ResponseBody
    public BSResult updatePrivilege(Integer[] ids, Integer roleId){

        BSResult result= rolePrivilegeService.updatePrivRole(ids,roleId);
        return result;

    }





}
